package interview.questions.删除任意给出的字符;

/**
 * 问题：
 * <p>
 * String中是如何删除指定字符
 */
public class Solution {
    /**
     * 通过循环从前往后遍历，如果不是要删除的字符则加到处理后的字符串中
     * @param sourceString
     * @param chElemData
     * @return
     */
    public static String deleteCharString0(String sourceString, char chElemData) {
        String deleteString = "";
        for (int i = 0; i < sourceString.length(); i++) {
            if (sourceString.charAt(i) != chElemData) {
                deleteString += sourceString.charAt(i);
            }
        }
        return deleteString;
    }

    /**
     * 通过循环确定要删除字符的位置索引，然后通过分割字符串的形式，将子字符串拼接，注意最后一段子字符串和源字符串中没有要删除字符的情况
     */
    public static String deleteCharString1(String sourceString, char chElemData) {
        String deleteString = "";
        int iIndex = 0;
        for (int i = 0; i < sourceString.length(); i++) {
            if (sourceString.charAt(i) == chElemData) {
                if (i > 0) {
                    deleteString += sourceString.substring(iIndex, i);
                }
                iIndex = i + 1;
            }
        }
        if (iIndex <= sourceString.length()) {
            deleteString += sourceString.substring(iIndex, sourceString.length());
        }
        return deleteString;
    }

    /**
     *本次采用 stringBuffer 类中的 append 方法进行操作
     */
    public static String deleteCharString2(String sourceString, char chElemData) {
        StringBuffer stringBuffer = new StringBuffer("");
        for (int i = 0; i < sourceString.length(); i++) {
            if (sourceString.charAt(i) != chElemData) {
                stringBuffer.append(sourceString.charAt(i));
            }
        }
        return stringBuffer.toString();
    }

}
